package com.cl.cloud.binlog.parser;

import com.cl.cloud.binlog.constant.EventEntityType;
import com.cl.cloud.binlog.tableMeta.ColumnMetaData;
import com.cl.cloud.binlog.tableMeta.TableMetaEntity;
import com.cl.cloud.binlog.tableMeta.TableMetaFactory;
import com.cl.cloud.binlog.util.CommonConverterProcessorUtil;
import com.cl.core.util.JsonUtil;
import com.github.shyiko.mysql.binlog.event.DeleteRowsEventData;
import com.github.shyiko.mysql.binlog.event.Event;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @description:
 * @author: liuzijian
 * @time: 2021-12-21 16:07
 */
public class DeleteEventParser implements IEventParser {

    private TableMetaFactory tableMetaFactory;

    public DeleteEventParser(TableMetaFactory tableMetaFactory) {
        this.tableMetaFactory = tableMetaFactory;
    }

    @Override
    public List<EventEntity> parse(Event event) {
        DeleteRowsEventData deleteRowsEventData = event.getData();
        TableMetaEntity tableMetaEntity = tableMetaFactory.getTableMetaEntity(deleteRowsEventData.getTableId());
        if (tableMetaEntity == null) {
            return null;
        }
        List<EventEntity> eventEntityList = new ArrayList<>();
        List<Serializable[]> rows = deleteRowsEventData.getRows();
        rows.forEach(rowMap -> {
            List<ColumnMetaData> columnMetaDataList = tableMetaEntity.getColumnMetaDataList();
            LinkedHashMap<String, String> after = CommonConverterProcessorUtil.convertToMap(rowMap, columnMetaDataList);

            EventEntity eventEntity = new EventEntity();
            eventEntity.setEvent(event);
            eventEntity.setEventEntityType(EventEntityType.DELETE);
            eventEntity.setDatabaseName(tableMetaEntity.getDbName());
            eventEntity.setTableName(tableMetaEntity.getTableName());
            eventEntity.setColumns(columnMetaDataList);
            eventEntity.setChangeAfter(new ArrayList<>(after.values()));
            eventEntity.setChangeAfterEntity(JsonUtil.toPojo(after,tableMetaEntity.getEntityClass()));
            eventEntityList.add(eventEntity);
        });
        return eventEntityList;
    }
}
